package com.antifly.common.handler;

import com.antifly.common.annotation.JcBigDecConvert;
import com.antifly.common.enums.UnitConvertType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * 单位转换处理逻辑
 *
 * @author LuoJiaHui
 * @date 2023/3/27 19:41
 * @description
 */
public class UnitConvertHandler {

    private UnitConvertHandler() {
    }

    private static Logger logger = LoggerFactory.getLogger(UnitConvertHandler.class);

    public static <T> void unitAnnotateConvert(List<T> list) {
        for (T t : list) {
            // 获取属性字段
            Field[] declaredFields = t.getClass().getDeclaredFields();
            for (Field declaredField : declaredFields) {
                try {
                    if (declaredField.getName().equals("serialVersionUID")) {
                        continue;
                    }
                    // 取出字段注解标记
                    JcBigDecConvert myFieldAnn = declaredField.getAnnotation(JcBigDecConvert.class);
                    if (Objects.isNull(myFieldAnn)) {
                        continue;
                    }
                    // 获取注解标记转换类型
                    UnitConvertType unitConvertType = myFieldAnn.name();
                    declaredField.setAccessible(true);
                    Object o = declaredField.get(t);
                    // 对应类型转换
                    if (Objects.nonNull(o)) {
                        BigDecimal bigDecimal = new BigDecimal(0);
                        switch (unitConvertType) {
                            case B:
                                bigDecimal = ((BigDecimal) o).divide(new BigDecimal(10000)).setScale(2,
                                        BigDecimal.ROUND_HALF_UP);
                                break;
                            case R:
                                // 自定义精度
                                int digitCapacity = myFieldAnn.digitCapacity();
                                bigDecimal = ((BigDecimal) o).setScale(digitCapacity, BigDecimal.ROUND_HALF_UP);
                                break;
                            case PER_MILLE:
                                bigDecimal = ((BigDecimal) o).multiply(new BigDecimal(1000)).setScale(2,
                                        BigDecimal.ROUND_HALF_UP);
                                break;
                            case PERCENTAGE:
                                bigDecimal = ((BigDecimal) o).multiply(new BigDecimal(100)).setScale(2,
                                        BigDecimal.ROUND_HALF_UP);
                                break;
                            default:
                                break;
                        }
                        declaredField.set(t, bigDecimal);
                    }
                } catch (Exception ex) {
                    logger.error("处理失败");
                }
            }
        }
    }
}
